/**
 * BoardAction.java
 */
package com.prs.crm.action.document.board;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.courser.ui.TreeNode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.Attach;
import com.prs.crm.context.FileUtil;
import com.prs.crm.domain.Attachment;
import com.prs.crm.domain.document.board.Board;
import com.prs.crm.domain.document.electron.Electron;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.sys.DocumentAdmin;
import com.prs.crm.domain.sys.FileTypeMaintain;
import com.prs.crm.domain.sys.ToolUrl;
import com.prs.crm.service.document.board.BoardService;
import com.prs.crm.service.sys.FileTypeMaintainService;
import com.prs.crm.service.sys.ToolUrlService;

/**
 * @author ZhuDongMei
 * @E-mail:1223984339@qq.com
 * @qq:1223984339
 * @version 创建时间：2011-3-16 上午11:12:28 简单说明
 */

public class BoardAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private Board board;
	private BoardService boardService;
	private PaginationSupport pagination;
	private Collection<TreeNode> nodes;
	private File upload;
	private String uplodS;
	private String uploadFileName;
	private Integer[] boardIds;
	private String netWorkIds;
	private Integer[] netIds;
	private FileTypeMaintainService fileTypeMaintainService;

	public FileTypeMaintainService getFileTypeMaintainService() {
		return fileTypeMaintainService;
	}

	public void setFileTypeMaintainService(
			FileTypeMaintainService fileTypeMaintainService) {
		this.fileTypeMaintainService = fileTypeMaintainService;
	}

	public Integer[] getNetIds() {
		return netIds;
	}

	public void setNetIds(Integer[] netIds) {
		this.netIds = netIds;
	}

	public String getNetWorkIds() {
		return netWorkIds;
	}

	public void setNetWorkIds(String netWorkIds) {
		this.netWorkIds = netWorkIds;
	}

	public Board getBoard() {
		return board;
	}

	public void setBoard(Board board) {
		this.board = board;
	}

	public BoardService getBoardService() {
		return boardService;
	}

	public void setBoardService(BoardService boardService) {
		this.boardService = boardService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public Collection<TreeNode> getNodes() {
		return nodes;
	}

	public void setNodes(Collection<TreeNode> nodes) {
		this.nodes = nodes;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUplodS() {
		return uplodS;
	}

	public void setUplodS(String uplodS) {
		this.uplodS = uplodS;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public Integer[] getBoardIds() {
		return boardIds;
	}

	public void setBoardIds(Integer[] boardIds) {
		this.boardIds = boardIds;
	}

	@Action("listNetWork")
	public String listNetWork() {

		return SUCCESS;
	}

	@Action("listShare")
	public String listShare() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Board.class).add(Restrictions.isNull("parent"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getBoardService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action(value = "loadBoardTree", results = { @Result(name = "success", type = "json", params = {
			"root", "nodes" }) })
	public String loadBoardTree() {
		nodes = new ArrayList<TreeNode>();
		Collection<Board> docs = this.getBoardService().getRootBoard();
		for (Board doc : docs) {
			if (doc.getUpState() == 1) {
				TreeNode node = new TreeNode();
				node.setId(String.valueOf(doc.getId()));
				node.setText(doc.getName());
				addChildNode(doc, node);
				nodes.add(node);
			}

		}
		return SUCCESS;
	}

	private void addChildNode(Board doc, TreeNode parentnode) {
		if (doc.getChilds() != null) {
			for (Board document : doc.getChilds()) {
				if ("文件夹".equals(document.getType().trim())) {
					if (doc.getUpState() == 1) {
						TreeNode node = new TreeNode();
						node.setId(String.valueOf(document.getId()));
						node.setText(document.getName());
						parentnode.addChildNode(node);
						addChildNode(document, node);
					}
				}
			}
		}
	}

	@Action(value = "loadNetWorkTrees", results = { @Result(name = "success", type = "json", params = {
			"root", "nodes" }) })
	public String loadNetWorkTrees() {
		nodes = new ArrayList<TreeNode>();
		Collection<Board> docs = this.getBoardService().getRootBoard();
		for (Board netWork : docs) {
			if (netWork.getUpState() == 1) {
				TreeNode node = new TreeNode();
				node.setId(String.valueOf(netWork.getId()));
				node.setText(netWork.getName());
				addChildNodes(netWork, node);
				nodes.add(node);
			}
		}
		return SUCCESS;
	}

	private void addChildNodes(Board netWork, TreeNode parentnode) {
		if (netWork.getChilds() != null) {
			for (Board document : netWork.getChilds()) {
				if ("文件夹".equals(document.getType().trim())) {
					if (netWork.getUpState() == 1) {
						TreeNode node = new TreeNode();
						node.setId(String.valueOf(document.getId()));
						node.setText(document.getName());
						parentnode.addChildNode(node);
						addChildNodes(document, node);
					}
				}
			}
		}
	}

	@Action(value = "saveFolder", results = {
			@Result(name = "success", type = "redirect", location = "listNetWork"),
			@Result(name = "error", type = "chain", location = "editFolder") })
	public String saveFolder() {
		if ("".equals(board.getName())) {
			this.addActionError("目录名称不能为空！");
			return ERROR;
		}
		if (board.getParent() == null) {
			this.addActionError("请选择上级文件夹！");
			return ERROR;
		}
		String path = board.getParent().getPath() + "/" + board.getName();
		System.out.println(path);
		File objFile = new File(path);
		objFile.mkdirs();
		board.setTime(new Date());
		board.setType("文件夹");
		board.setPath(path);
		board.setUpPerson(AppContext.getAccountContext().currentUser());
		this.getBoardService().save(board);
		return SUCCESS;
	}

	@Action(value = "newFolder", results = {
			@Result(name = "success", type = "redirect", location = "editFolder"),
			@Result(name = "error", type = "chain", location = "listFolder") })
	public String newFolder() {
		List<Board> boards = this.getBoardService().getAllBoards();
		if (boards.size() == 0) {
			return ERROR;
		}
		return SUCCESS;
	}

	@Action("listFolder")
	public String listFolder() {
		return SUCCESS;
	}

	@Action("editFolder")
	public String editFolder() {
		return SUCCESS;
	}

	@Action("editManager")
	public String editManager() {
		return SUCCESS;
	}

	@Action(value = "updateManager", results = {
			@Result(name = "success", type = "redirect", location = "editManager?board=${board.getId()}"),
			@Result(name = "error", type = "chain", location = "listShare") })
	public String updateManager() {
		if (boardIds == null) {
			this.addActionError("请选择数据行！");
			return ERROR;
		} else if (boardIds.length > 1) {
			this.addActionError("只能操作一行！");
			return ERROR;
		} else {
			this.board = this.getBoardService().get(boardIds[0]);
			return SUCCESS;
		}
	}

	@Action(value = "removeManager", results = {
			@Result(name = "success", type = "redirect", location = "listShare"),
			@Result(name = "error", type = "chain", location = "listShare") })
	public String removeManager() {
		// System.out.println(board.getPath());
		// if (board.getChilds() == null) {
		// File file = new File(board.getPath());
		// if (file.exists()) {
		// file.delete();
		// }
		// }else{
		// Collection<Board> boards = board.getChilds();
		// for(Board boar:boards){
		// File file = new File(boar.getPath());
		// if(file.exists()){
		// file.delete();
		// }
		// }
		// File file = new File(board.getPath());
		// if (file.exists()) {
		// file.delete();
		// }
		// }
		if (boardIds != null) {
			this.getBoardService().batchRemove(boardIds);
			return SUCCESS;
		} else {
			this.addActionError("请选择数据行！");
			return ERROR;
		}

	}

	@Action("listNetWorkByFolder")
	public String listNetWorkByFolder() {
		Person cuPerson = AppContext.getAccountContext().currentUser();
		List<Board> d = this.getBoardService().getAllBoards();
		for (Board ob : d) {
			if (ob.getRecorder().getResume().getName().equals(
					cuPerson.getResume().getName())) {
				ob.setViState(1);// 1表示有访问权限，2没有访问权限
				ob.setUpState(1);// 1表示有修改权限，2没有修改权限
				this.getBoardService().submit(ob);
			} else {
				if (ob.getPersonId() == null
						|| "".equals(ob.getPersonId().trim())) {
					ob.setUpState(1);
					this.getBoardService().submit(ob);
				} else {
					String[] per = ob.getPersonId().split(",");
					for (String pers : per) {
						if (cuPerson.getId().equals(Integer.parseInt(pers))) {
							ob.setUpState(1);
							this.getBoardService().submit(ob);
							break;
						} else {
							ob.setUpState(2);

							this.getBoardService().submit(ob);
						}
					}
				}
				if (ob.getVisitId() == null
						|| "".equals(ob.getVisitId().trim())) {
					ob.setViState(1);
					this.getBoardService().submit(ob);
				} else {
					String[] per = ob.getVisitId().split(",");
					for (String pers : per) {
						if (cuPerson.getId().equals(Integer.parseInt(pers))) {
							ob.setViState(1);
							this.getBoardService().submit(ob);
							break;
						} else {
							ob.setViState(2);
							this.getBoardService().submit(ob);
						}
					}
				}
			}
		}
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Board.class).add(Restrictions.isNull("parent"));
		criteria.add(Restrictions.eq("viState", 1));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getBoardService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listNetWorkByFolders")
	public String listNetWorkByFolders() {
		Person cuPerson = AppContext.getAccountContext().currentUser();
		List<Board> d = this.getBoardService().getAllBoards();
		for (Board ob : d) {
			if (ob.getRecorder().getResume().getName().equals(
					cuPerson.getResume().getName())) {
				ob.setViState(1);// 1表示有访问权限，2没有访问权限
				ob.setUpState(1);// 1表示有修改权限，2没有修改权限
				this.getBoardService().submit(ob);
			} else {
				if (ob.getPersonId() == null
						|| "".equals(ob.getPersonId().trim())) {
					ob.setUpState(1);
					this.getBoardService().submit(ob);
				} else {
					String[] per = ob.getPersonId().split(",");
					for (String pers : per) {
						if (cuPerson.getId().equals(Integer.parseInt(pers))) {
							ob.setUpState(1);
							this.getBoardService().submit(ob);
							break;
						} else {
							ob.setUpState(2);
							this.getBoardService().submit(ob);
						}
					}
				}
				if (ob.getVisitId() == null
						|| "".equals(ob.getVisitId().trim())) {
					ob.setViState(1);
					this.getBoardService().submit(ob);
				} else {
					String[] per = ob.getVisitId().split(",");
					for (String pers : per) {
						if (cuPerson.getId().equals(Integer.parseInt(pers))) {
							ob.setViState(1);
							this.getBoardService().submit(ob);
							break;
						} else {
							ob.setViState(2);
							this.getBoardService().submit(ob);
						}
					}
				}
			}
		}
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Board.class).add(Restrictions.eq("parent", board));
		criteria.add(Restrictions.eq("viState", 1));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getBoardService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action(value = "saveManager", results = {
			@Result(name = "success", type = "redirect", location = "listShare"),
			@Result(name = "error", type = "chain", location = "editManager") })
	public String saveManager() {
		if ("".equals(board.getPath())) {
			this.addActionError("共享路径不能为空！");
			return ERROR;
		}
		if ("".equals(board.getName())) {
			this.addActionError("共享名称不能为空！");
			return ERROR;
		}
		File objFile = new File(board.getPath());
		if (objFile.exists()) {
			objFile.delete();
		}
		objFile.mkdirs();
		board.setType("文件夹");
		board.setUpPerson(AppContext.getAccountContext().currentUser());
		this.getBoardService().save(board);
		return SUCCESS;
	}

	@Action("listNetTree")
	public String listNetTree() {
		Person cuPerson = AppContext.getAccountContext().currentUser();
		List<Board> d = this.getBoardService().getAllBoards();
		for (Board ob : d) {
			if (ob.getRecorder().getResume().getName().equals(
					cuPerson.getResume().getName())) {
				ob.setViState(1);// 1表示有访问权限，2没有访问权限
				ob.setUpState(1);// 1表示有修改权限，2没有修改权限
				this.getBoardService().submit(ob);
			} else {
				if (ob.getPersonId() == null
						|| "".equals(ob.getPersonId().trim())) {
					ob.setUpState(1);
					this.getBoardService().submit(ob);
				} else {
					String[] per = ob.getPersonId().split(",");
					for (String pers : per) {
						if (cuPerson.getId().equals(Integer.parseInt(pers))) {
							ob.setUpState(1);
							this.getBoardService().submit(ob);
							break;
						} else {
							ob.setUpState(2);
							this.getBoardService().submit(ob);
						}
					}
				}
				if (ob.getVisitId() == null
						|| "".equals(ob.getVisitId().trim())) {
					ob.setViState(1);
					this.getBoardService().submit(ob);
				} else {
					String[] per = ob.getVisitId().split(",");
					for (String pers : per) {
						if (cuPerson.getId().equals(Integer.parseInt(pers))) {
							ob.setViState(1);
							this.getBoardService().submit(ob);
							break;
						} else {
							ob.setViState(2);
							this.getBoardService().submit(ob);
						}
					}
				}
			}
		}
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Board.class).add(
				Restrictions.eq("parent", this.getBoardService().getBoardById(
						board.getId())));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getBoardService().listByPage(criteria,
				pagination));
		return SUCCESS;

	}

	@Action("editUpload")
	public String editUpload() {
		return SUCCESS;
	}

	@Action(value = "upload", results = {
			@Result(name = "success", type = "redirect", location = "listNetWork"),
			@Result(name = "error", type = "chain", location = "editUpload") })
	public String upload() {
		if (upload != null) {
			File file = new File(upload.getPath());
			try {
				long sizes = new FileInputStream(file).available();
				if ("0".equals(AppContext.getAccountContext().currentUser()
						.getUploadMaxVolume())
						|| "".equals(AppContext.getAccountContext()
								.currentUser().getUploadMaxVolume())) {
					this.board.setAttach(FileUtil.getInstance().createAttach(
							upload, uploadFileName));
					List<FileTypeMaintain> ft = this
							.getFileTypeMaintainService().getFileTypeMaintain(
									board.getAttach().getContentType());
					if (ft.size() > 0) {
						for (FileTypeMaintain fileTypeMaintain : ft) {
							board.setFileTypeMaintain(fileTypeMaintain);
							board.setType("other");
						}
					} else {
						board.setType("others");
					}
					board.setName(board.getAttach().getName());
					board.setSize(board.getAttach().getSize());
					board.setTime(new Date());
					if (board.getParent() == null) {
						this.addActionError("请选择上级文件夹！");
						return ERROR;
					}
					String path = board.getParent().getPath() + "/"
							+ board.getName();
					// File objFile = new File(path);
					// objFile.createNewFile();
					Attachment attach = FileUtil.getInstance().createAttach1(
							upload, uploadFileName);
					String path1 = attach.getPath();
					this.Copy(path1, path);
					board.setPath(path);
					board.setUpPerson(AppContext.getAccountContext()
							.currentUser());
					this.getBoardService().save(board);
					return SUCCESS;
				} else {
					long max = new Double(Double.parseDouble(AppContext
							.getAccountContext().currentUser()
							.getUploadMaxVolume()) * 1024 * 1024).longValue();

					if (sizes <= max) {
						this.board.setAttach(FileUtil.getInstance()
								.createAttach(upload, uploadFileName));
						List<FileTypeMaintain> ft = this
								.getFileTypeMaintainService()
								.getFileTypeMaintain(
										board.getAttach().getContentType());
						if (ft.size() > 0) {
							for (FileTypeMaintain fileTypeMaintain : ft) {
								board.setFileTypeMaintain(fileTypeMaintain);
								board.setType("other");
							}
						} else {
							board.setType("others");
						}
						board.setName(board.getAttach().getName());
						board.setSize(board.getAttach().getSize());
						if (board.getParent() == null) {
							this.addActionError("请选择上级文件夹！");
							return ERROR;
						}
						String path = board.getParent().getPath() + "/"
						+ board.getName();
						// File objFile = new File(path);
						// objFile.createNewFile();
						Attachment attach = FileUtil.getInstance().createAttach1(
								upload, uploadFileName);
						String path1 = attach.getPath();
						this.Copy(path1, path);
						board.setPath(path);
						board.setUpPerson(AppContext.getAccountContext()
								.currentUser());
						this.getBoardService().save(board);
						return SUCCESS;
					} else {
						this.addActionError("上传的附件太大！");
						return ERROR;
					}
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			this.addActionError("上传的附件不能为空！");
			return ERROR;
		}
		board.setName(board.getAttach().getName());
		board.setSize(board.getAttach().getSize());
		board.setUpPerson(AppContext.getAccountContext().currentUser());
		this.getBoardService().save(board);
		return SUCCESS;
	}

	/**
	 * 将上传文件复制到指定文件夹里去
	 */
	public static void Copy(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File file = new File(oldPath);
			if (file.exists()) {
				InputStream inStream = new FileInputStream(oldPath);
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			System.out.println("error");
			e.printStackTrace();
		}
	}

	@Action("editRenameFile")
	public String editRenameFile() {
		return SUCCESS;
	}

	@Action("editRenameFolder")
	public String editRenameFolder() {
		return SUCCESS;
	}

	@Action("editFile")
	public String editFile() {
		return SUCCESS;
	}

	@Action(value = "newFile", results = {
			@Result(name = "success", type = "redirect", location = "editFile"),
			@Result(name = "error", type = "chain", location = "listFile") })
	public String newFile() {
		List<Board> boards = this.getBoardService().getAllBoards();
		if (boards.size() == 0) {
			return ERROR;
		}
		return SUCCESS;
	}

	@Action("listFile")
	public String listFile() {
		return SUCCESS;
	}

	@Action("listKnow")
	public String listKnow() {
		return SUCCESS;
	}

	@Action(value = "saveFile", results = {
			@Result(name = "success", type = "redirect", location = "listNetWork"),
			@Result(name = "error", type = "chain", location = "editFile") })
	public String saveFile() throws IOException {
		if ("".equals(board.getName())) {
			this.addActionError("文件名不能为空！");
			return ERROR;
		}
		board.setTime(new Date());
		if (board.getParent() == null) {
			this.addActionError("请选择上级文件夹！");
			return ERROR;
		}
		String path;
		if ("Microsoft Word 文档".equals(board.getType())) {
			path = board.getParent().getPath() + "/" + board.getName() + ".doc";
		} else if ("Microsoft PowerPoint 幻灯片".equals(board.getType())) {
			path = board.getParent().getPath() + "/" + board.getName() + ".ppt";
		} else {
			path = board.getParent().getPath() + "/" + board.getName() + ".pdf";
		}
		board.setPath(path);
		File objFile = new File(path);
		if ("文件夹".equals(board.getType())) {
			objFile.mkdirs();
		} else {
			objFile.createNewFile();
		}
		board.setUpPerson(AppContext.getAccountContext().currentUser());
		this.getBoardService().save(board);
		return SUCCESS;
	}

	@Clew(results = { "error" })
	@Action(value = "removeBoard", results = {
			@Result(name = "success", type = "redirect", location = "listNetWork"),
			@Result(name = "error", type = "redirect", location = "listNetWork") })
	public String removeBoard() {
		System.out.println(board.getPath());
		if (board.getChilds().size() == 0) {
			File file = new File(board.getPath());
			if (file.exists()) {
				file.delete();
			}
			this.getBoardService().removeBoard(board.getId());
			return SUCCESS;
		} else {
			this.setPrompt("该文件下面有关联文件，不能删除该文件！");
			return ERROR;
		}
	}

	@Action("editMove")
	public String editMove() {
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "saveMove", results = {
			@Result(name = "success", type = "redirect", location = "listNetWork"),
			@Result(name = "error", type = "redirect", location = "listNetWork") })
	public String saveMove() {
		String file=board.getPath();
		String path1=board.getParent().getPath()+"/";
		this.Move(file, path1);
		board.setPath(path1+board.getName());
		this.getBoardService().submit(board);
		this.setPrompt("移动成功");
		return SUCCESS;
	}
	
	
	 public static void Move(String srcFile, String destPath)
	 {		
	 	File file=new File(srcFile);
        File dir = new File(destPath);
        if(dir.exists()) {
        	File fnew = new File(destPath +file.getName()); 
        	file.renameTo(fnew); 
        }
	 }
}
